import { Layers, Node, SpriteFrame, UITransform } from 'cc'

/**
 * 创建节点
 * @param name 节点名称
 * @param layerName 节点层级
 * @returns
 */
export const createUiNode = (name: string = '', layerName: string = 'UI_2D') => {
  const node = new Node(name)
  const transform = node.addComponent(UITransform)
  transform.setAnchorPoint(0, 1) // 锚点设置于左上角
  node.layer = 1 << Layers.nameToLayer(layerName) // 设置节点层级
  return node
}

/**
 * 随机获取瓦片的图片范围
 */
export const randomTileRange = (start: number, end: number) => {
  return Math.floor(Math.random() * (end - start) + start)
}

/** 对瓦片图片进行排序 因为顺序可能是乱的(10)(11)(12)(13)(9) */
const reg = /\((\d+)\)/
const getNumberWithInString = (str: string) => parseInt(str.match(reg)[1] || '0')
export const sortSpriteFrame = (spriteFrames: SpriteFrame[]) => {
  return spriteFrames.sort((a, b) => getNumberWithInString(a.name) - getNumberWithInString(b.name))
}

/** 生成唯一id */
export const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = (Math.random() * 16) | 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
